package com.gmcf.crypto.snd;

import com.alibaba.fastjson.JSONObject;
import com.gmcf.crypto.conf.ReadPrivateAndPubKeyFromProperties;
import com.gmcf.crypto.rcv.ReceiveGomeRequestContoller;
import com.gmcf.crypto.util.DemoSignUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

import static com.gmcf.crypto.rcv.ReceiveGomeRequestContoller.*;
import static com.gmcf.crypto.util.DemoSignUtil.*;

/**
 * @author zhangfuqiang3@gome.com.cn
 * @version 1.0
 * @date 2023/12/27
 * @description: 流量方平台回调国美
 **/
@Component
@Slf4j
public class SendGomeMsgHandler {

    @Autowired
    private ReadPrivateAndPubKeyFromProperties readKey;


    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");
    public final static OkHttpClient client = new OkHttpClient();

    // 发送给国美的请求数据
    public String post2Gome() throws Exception {
        // 1. 国美回调地址配置在配置文件
        String url = readKey.getUrlOne();
        // 2. 组装好接口对应的参数即可 此处为演示示例demo; 此步骤为业务逻辑
        JSONObject data = new JSONObject();
        data.putIfAbsent("orderStatus", "600");
        data.putIfAbsent("loanAmount", 8000);
        data.putIfAbsent("capitalBizNo","165660523801455100");
        data.putIfAbsent("yearRate", 0.3599);
        data.putIfAbsent("actualRepayAmount",8000);
        data.putIfAbsent("appointLoanName", "放款资方名称");
        data.putIfAbsent("capitalNo", "F6021");
        data.putIfAbsent("totalFeeAmount","1203.96");
        data.putIfAbsent("periods","12");
        data.putIfAbsent("loanNo","GMLOC12345678");
        data.putIfAbsent("repayTime","2022-07-17 16:13:58");
        data.putIfAbsent("loanBankCardNo","6123131414141");

        // 给国美回调的不需要data包装
        String dataString = getJsonString(data);
        LOGGER.info("回调给国美的业务明文数据是:{}",dataString);
        String random = DemoSignUtil.getRandom();
        String encryptRandomKey = encryptByPublicKey4Pkcs5(random.getBytes(Charset.forName("UTF-8")), readKey.getGomePublicKey());
        // 3. 加密给国美的真正data报文
        String reqData = encrypt4Base64(dataString, random);
        // 签名
        String signToGome = sign(data.toString().getBytes(Charset.forName("UTF-8")), readKey.getMyPrivateKey());
        ReceiveGomeRequestContoller.ReqHead reqHead = new ReceiveGomeRequestContoller.ReqHead(encryptRandomKey, signToGome);
        String json = JSONObject.toJSONString(new ReceiveGomeRequestContoller.Resp(reqHead, reqData));
        LOGGER.info("回调给国美的加密响应数据:{}",json);
        String rspStr = null;
        // 4 . 组装参数发给国美侧
        RequestBody body = RequestBody.create(json, JSON); // new
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            // 5. 接受国美侧响应
            rspStr = getRspStr(response);
            LOGGER.info("回调后接收到国美信息是:{}", rspStr);
        }

        return rspStr;
    }

    @NotNull
    private static String getRspStr(Response response) throws IOException {
        return response.body().string();
    }

}
